package com.example.diancai.util;

import com.example.diancai.consts.RequestAttributeKeyConst;
import com.example.diancai.dto.CurrentPlayer;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Map;

public class AuthUtil {

    private final static ThreadLocal<Map<String, Object>> holder = new ThreadLocal<>();

    public static boolean isLogin() {
        HttpServletRequest request = ContextUtil.getRequest();
        if (request == null) {
            return false;
        }
        return request.getAttribute(RequestAttributeKeyConst.USERINFO) != null;
    }

    /**
     * 获取当前用户
     */
    public static CurrentPlayer getCurrPlayer() {
        HttpServletRequest request = ContextUtil.getRequest();
        if (request == null) {
            return null;
        }
        CurrentPlayer competenceUser = (CurrentPlayer) request.getAttribute(RequestAttributeKeyConst.USERINFO);
        return competenceUser;
    }


    /**
     * 获取当前用户id
     *
     * @return
     */
    public static Integer getCurrPlayerId() {
        CurrentPlayer currUser = getCurrPlayer();
        if (currUser == null)
            return null;
        return currUser.getId();
    }


    /**
     * 获取当前用户id
     *
     * @return
     */
    public static String getCurrNickName() {
        CurrentPlayer currUser = getCurrPlayer();
        if (currUser == null)
            return null;
        return currUser.getWxUsername();
    }


    public static String getToken() {
        HttpServletRequest request = ContextUtil.getRequest();
        return getToken(request);
    }

    public static String getToken(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token == null)
            token = request.getHeader("token");
        return token;
    }


}
